package com.zhw.controller;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.logging.Logger;

/**
 * Created by Administrator on 2018/9/20.
 */
@Controller
@RequestMapping("api/wechat")
//@Slf4j
public class WechatController {
    @Autowired
    private WxMpService wxMpService;

    private org.slf4j.Logger logger= LoggerFactory.getLogger(WechatController.class);



    /**
     * 验证开发者配置的服务器，介入微信服务器：
     * 开发者提交信息后，微信服务器将发送GET请求到填写的服务器地址URL上:http://120.78.206.253/api/wechat
     * 开发者通过检验signature对请求进行校验（下面有校验方式）。若确认此次GET请求来自微信服务器，
     * 请原样返回echostr参数内容，则接入生效，成为开发者成功，否则接入失败。
     * @param request
     * @return
     */
    @RequestMapping(value = "")
    public String verifyServer(HttpServletRequest request){

        logger.info("收到微信服务器验证get请求");

        //微信服务器get传递的参数
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");

        //微信工具类
        WxMpService wxService=new WxMpServiceImpl();

        //注入token的配置参数
        /**
         * 生产环境 建议将WxMpInMemoryConfigStorage持久化
         */
        WxMpInMemoryConfigStorage wxConfigProvider=new WxMpInMemoryConfigStorage();
        //注入token值
        wxConfigProvider.setToken("weixin1");

        wxService.setWxMpConfigStorage(wxConfigProvider);
        //会返回给微信服务器
        boolean flag=wxService.checkSignature(timestamp, nonce, signature);
        if(flag){
            return "接入微信服务器成功";
        }
        return "接入微信服务器失败";
    }

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){
//        String url = "http://xxx.natapp.cn/wechat/userInfo";
        String url = "http://www.cqcity.xin/wechat/userInfo";
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl));
        logger.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        return "redirect:" + redirectURL;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        logger.info("【微信网页授权】code={}", code);
        logger.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            logger.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        logger.info("【微信网页授权】openId={}", openId);
        return "redirect:" + returnUrl + "?openid=" + openId;
    }

}
